<?php

vendor('mail/mail');
vendor('mail/stored_attachment');

class SendMail extends AppModel
{
	var $name = 'SendMail';

	var $useTable = false;

	/**
	 * Немедленная отправка.
	 *
	 * @param MailModel $mail
	 * @param array $params Дополнительные параметры
	 */
	function send(MailModel $mail, $params = array())
	{
		if (! Mailer::send($mail)) {
			throw new Exception();
		}
		$params['send_date'] = Date::Unix2SQL(time());
		$this->afterSend($mail, $params);
	}

	/**
	 * Отложенная отправка.
	 *
	 * @param MailModel $mail
	 * @param array $params Дополнительные параметры
	 */
	function delayed_send(MailModel $mail, $params = array())
	{
		$Email =& $this->getModel('Email'); /* @var $Email Email */

		if (! $Email->save($Email->create(array($Email->name => array(
			'data' => serialize($mail),
			'params' => serialize($params),
			'created' => Date::Unix2SQL(time()),
		)))))
		{
			throw new DBException("Could not send email");
		}
	}

	/**
	 * Отправка всей очереди сообщений.
	 */
	function send_queue()
	{
	    set_time_limit(0);
        loadModel('Blob');
		$Email =& $this->getModel('Email'); /* @var $Email Email */
		$emails = $Email->generateList();
        if (is_array($emails) && count($emails) > 0) {
			foreach ($emails as $id => $created) {
				$Email->rel();
				$email = $Email->read(null, $id);

				if (!empty($email[$Email->name])) {
					try {
                        $message = unserialize($email[$Email->name]['data']);
                        $params = unserialize($email[$Email->name]['params']);
						$this->send($message, $params);
						$Email->del($id);
					} catch (Exception $e) {
						$bad_retries = !empty($email[$Email->name]['retries']) ? $email[$Email->name]['retries'] : 0;
						$bad_retries++;
						$data = array(
							$Email->primaryKey => $id,
							'retries' => $bad_retries,
							'last_try_date' => Date::Unix2SQL(time()),
						);

						$Email->save(array($Email->name => $data));
					}
				}
			}
		}
	}

	/**
	 * Обработчик события, наступающего после успешной отправки письма
	 *
	 * @param MailModel $mail Отправленное письмо
	 * @param array $params Дополнительные параметры
	 */
	protected function afterSend(MailModel $mail, $params = array())
	{
        $this->getModel('Sending')->sended($mail, $params);
	}

	function sendReport($params)
	{
	    if (empty($params['blob']['id']) || empty($params['report']) || empty($params['reporting']) || empty($params['client_admin'])) {
            throw new ArgException();
	    }
	    $blob          = $params['blob'];
	    $candidate     = @$params['candidate'];
	    $client        = $params['client'];
	    $report        = $params['report'];
	    $reporting     = $params['reporting'];
	    $norm          = $params['norm'];
	    $test          = @$params['test'];
	    $testing       = @$params['testing'];
	    $client_admin  = @$params['client_admin'];

        $SendMail = $this->getModel('SendMail'); /* @var $SendMail SendMail */
        $mail = new MailModel();
        $mail->from = ADMIN_EMAIL;
        $mail->fromName = 'admin';
        $mail->to = $client_admin['email'];

        $old_lang = Configure::read('Config.language');
        I18n::getInstance()->l10n->get(Configure::read('email_language'));

        $mail->message = __d(null, 'Report is generated. Find file at the e-mail attachments', true);
        $mail->subject = __d(null, 'Report is generated', true);

        I18n::getInstance()->l10n->get($old_lang);

        loadModel('Blob');
        $attachment = new StoredMailAttachmentModel('Blob', $blob['id']);
        $attachment->ContentType = 'application/pdf';
        // TODO: изменить имя репорта (file_name)
        $attachment->FileName = 'report.pdf';

        $mail->attachments[] = $attachment;

        $mail_params['mode']            = 'generate_report';
        $mail_params['report_id']       = $report['id'];
        $mail_params['reporting_id']    = $reporting['id'];
        $mail_params['candidate_id']    = @$candidate['id'];
        $mail_params['client_id']       = $client['id'];
        $mail_params['test_id']         = @$test['id'];
        $mail_params['testing_id']      = @$testing['id'];
        $mail_params['client_admin_id'] = @$client_admin['id'];
        if (Auth::o()->is('admin')) {
            $mail_params['author_admin_id'] = Auth::o()->realId();
        } elseif (Auth::o()->is('client_admin')) {
            $mail_params['author_client_admin_id'] = Auth::o()->realId();
        }

        if (!empty($params['delayed'])) {
            $SendMail->delayed_send($mail, $mail_params);
        } else {
            $SendMail->send($mail, $mail_params);
        }
	}

	function sendNoticeOnCandidateTested($params)
	{
	    if (empty($params['candidate']) || empty($params['test']) || empty($params['testing']) || empty($params['client_admin'])) {
            throw new ArgException();
	    }
	    $candidate     = $params['candidate'];
	    $test          = $params['test'];
	    $testing       = $params['testing'];
	    $client_admin  = $params['client_admin'];
        $mail_params = array();
        $mail_params['author_admin_id'] = @$params['author_admin_id'];
        $mail_params['author_client_admin_id'] = @$params['author_client_admin_id'];

        $SendMail = $this->getModel('SendMail'); /* @var $SendMail SendMail */
        $mail = new MailModel();
        $mail->from = ADMIN_EMAIL;
        $mail->fromName = 'admin';
        $mail->to = $client_admin['email'];

        $old_lang = Configure::read('Config.language');
        I18n::getInstance()->l10n->get(Configure::read('email_language'));

        $mail->subject = __d('email', 'Letter from T&Q', true);
        $mail->message = sprintf(__d('email', 'Notice on candidate tested', true),
            $candidate['surname']." ".$candidate['name'],
            $test['name']
        );

        I18n::getInstance()->l10n->get($old_lang);

        $mail_params['mode']            = 'end_testing';
        $mail_params['test_id']         = $test['id'];
        $mail_params['testing_id']      = $testing['id'];
        $mail_params['candidate_id']    = $candidate['id'];
        $mail_params['client_admin_id'] = @$client_admin['id'];
        $mail_params['client_id']       = $candidate['client_id'];

        if (!empty($params['delayed'])) {
            $SendMail->delayed_send($mail, $mail_params);
        } else {
            $SendMail->send($mail, $mail_params);
        }
	}

	function sendOfferOnTesting($params)
	{
	    if (empty($params['candidate']) || empty($params['test']) || empty($params['testing']) || empty($params['client'])) {
            throw new ArgException();
	    }

	    $candidate = $params['candidate'];
	    $test      = $params['test'];
	    $testing   = $params['testing'];
	    $client    = $params['client'];

        $SendMail = $this->getModel('SendMail'); /* @var $SendMail SendMail */
        $mail = new MailModel();
        $mail->from = ADMIN_EMAIL;
        $mail->fromName = 'admin';
        $mail->to = $candidate['email'];

        $old_lang = Configure::read('Config.language');
        I18n::getInstance()->l10n->get(Configure::read('candidate_email_language'));

        $mail->subject = __d('email', 'Letter from T&Q', true);
        $mail->message = sprintf(__d('email', 'Email message %s', true),
/*name*/     $candidate['surname']." ".$candidate['name'],
/*questName*/$test['name'],
/*password*/ $testing['password'],
/*link*/     Router::url(array('controller' => 'applet', 'action' => 'go', 'auth' => $testing['auth_link']), true)
        );

        I18n::getInstance()->l10n->get($old_lang);

        $mail_params['mode']            = 'offer_on_testing';
        $mail_params['test_id']         = $test['id'];
        $mail_params['testing_id']      = $testing['id'];
        $mail_params['candidate_id']    = $candidate['id'];
        $mail_params['client_id']       = $client['id'];
        if (Auth::o()->is('admin')) {
            $mail_params['author_admin_id'] = Auth::o()->realId();
        } elseif (Auth::o()->is('client_admin')) {
            $mail_params['author_client_admin_id'] = Auth::o()->realId();
        }

        if (!empty($params['delayed'])) {
            $SendMail->delayed_send($mail, $mail_params);
        } else {
            $SendMail->send($mail, $mail_params);
        }
	}
}

?>